package video.background.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.AES;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import video.background.Controller.ControllerParams.AddUsersParams;
import video.background.Controller.ControllerParams.DeleteTeamParams;
import video.background.Controller.ControllerParams.UpdataUsersParams;
import video.background.Controller.View.TeamShowUserView;
import video.background.Dao.TeamDao;
import video.background.Dao.UserDao;
import video.background.Dao.UserGroupDao;
import video.background.Model.FileTable;
import video.background.Model.Team;
import video.background.Model.UserGroup;
import video.background.Model.Users;
import video.background.Utils.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/team")
@CrossOrigin(origins = "*", maxAge = 3600)
@Api(tags = "团队成员管理相关接口")
public class TeamController {
    @Autowired
    private TeamDao teamDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserGroupDao userGroupDao;
    @PostMapping("/deleteUsers")
    @ApiOperation("踢出团队成员")
    public Result deleteUsers(@RequestHeader String Authorization, @RequestBody DeleteTeamParams data){
        Long be_userId = Long.valueOf(data.getBe_userId());
        String groupId = data.getGroupId();
        //解析删除请求发起人token
        Long userId = JwtUtils.decoderToken(Authorization);
        if(userId == null)
            return Result.Error("删除发起人数据不全，请检查数据",null);
        if(be_userId == null)
            return Result.Error("被删除人数据不全，请检查数据",null);
        //查看删除请求发起人权限
        LambdaQueryWrapper<UserGroup> ulqw = new LambdaQueryWrapper<>();
        ulqw.eq(UserGroup::getUserId,userId).eq(UserGroup::getGroupId,groupId);
        UserGroup userGroup = userGroupDao.selectOne(ulqw);//找到删除请求发起人
        if (userGroup == null) return Result.Error("您不在该团队，请检查数据",null);

        //查看被删除人权限
        LambdaQueryWrapper<UserGroup> be_ulqw = new LambdaQueryWrapper<>();
        be_ulqw.eq(UserGroup::getUserId,be_userId).eq(UserGroup::getGroupId,groupId);
        UserGroup be_userGroup = userGroupDao.selectOne(be_ulqw);//找到被删除人
        if (be_userGroup == null) return Result.Error("被删除者不在该团队，请检查数据",null);
        //删除团队成员
        //如果是创始人，则可以删除任何人
        if(userGroup.getUserRole() == '0') {
            Team team = teamDao.selectById(groupId);
            team.setCurrentMemberSize(team.getCurrentMemberSize() - 1);
            teamDao.updateById(team);
            userGroupDao.delete(be_ulqw);
            MessageUtils.sendMessage(be_userId,userDao.selectById(be_userId).getUserName(),8, Long.valueOf(groupId));
            return Result.Success("删除成员成功",null);
        } else if(userGroup.getUserRole() == '1') {
            // 如果是管理员，则只能删除普通用户
            Team team = teamDao.selectById(groupId);
            team.setCurrentMemberSize(team.getCurrentMemberSize() - 1);
            teamDao.updateById(team);
            if (be_userGroup.getUserRole() == '1' || be_userGroup.getUserRole() == '0')
                return Result.Error("删除发起人权限不够，请检查数据",null);
            userGroupDao.delete(be_ulqw);
            MessageUtils.sendMessage(be_userId,userDao.selectById(be_userId).getUserName(),8, Long.valueOf(groupId));
            return Result.Success("删除成员成功",null);
        }else{
            return Result.Error("权限不够，请检查数据",null);
        }
    }

//    @ApiOperation("根据邀请码查询团队信息")
//    @GetMapping("/getTeamsByAccessCode")
//    public Result getTeamsByAccessCode(@RequestParam String accessCode){
//        LambdaQueryWrapper<Team> tlqw = new LambdaQueryWrapper<>();
//        tlqw.eq(Team::getAccessCode, accessCode);
//        List<Team> teams = teamDao.selectList(tlqw);
//        return Result.Success("请求成功！", teams);
//    }

    @ApiOperation("成员加入团队")
    @PostMapping("/addTeam")
    public Result addUsers(@RequestHeader String Authorization, @RequestBody Map<String,String>data){
        String accessCode = data.get("accessCode");
        //解析token
        Long userId = JwtUtils.decoderToken(Authorization);
        if(Authorization == null || Authorization.equals("") || userId == null)
            return Result.Error("申请人数据不全",null);
        LambdaQueryWrapper<Team> tlqw = new LambdaQueryWrapper<>();
        tlqw.eq(Team::getAccessCode,accessCode);
        Team team = teamDao.selectOne(tlqw);
        if(team == null) return Result.Error("未查询到团队信息！", null);
        //查询是否已经加入团队
        LambdaQueryWrapper<UserGroup> uglqw = new LambdaQueryWrapper<>();
        uglqw.eq(UserGroup::getUserId,userId).eq(UserGroup::getGroupId,team.getGroupId());
        UserGroup userGroup1 = userGroupDao.selectOne(uglqw);
        if (userGroup1 != null) return Result.Error("您已经加入该团队，不能重复加入，请检查数据",null);
        //查询团队剩余容量是否大于等于1
        LambdaQueryWrapper<UserGroup> uglqw1 = new LambdaQueryWrapper<>();
        uglqw1.eq(UserGroup::getGroupId,team.getGroupId());
        List<UserGroup> userGroups = userGroupDao.selectList(uglqw1);
        if (userGroups.size() == 10) return Result.Error("该团队成员已满，无法加入",null);
        UserGroup userGroup = new UserGroup(null,'2',userId,team.getGroupId().toString(), 1, '0');
        // 更新当前团队信息
        userGroupDao.insert(userGroup);
        team.setCurrentMemberSize(team.getCurrentMemberSize() + 1);
        teamDao.updateById(team);
        MessageUtils.sendMessage(userId,userDao.selectById(userId).getUserName(),6,team.getGroupId());
        return Result.Success("加入成功！",null);
    }


    @PostMapping("/updateUsers")
    @ApiOperation("修改团队成员权限")
    public Result UpdataUsers(@RequestHeader String Authorization, @RequestBody UpdataUsersParams data) {
        String groupId = data.getGroupId();
        String be_userId = data.getBe_userId();
        char newUserRole = data.getNewUserRole();
        if(groupId == null || be_userId == null) return Result.Error("数据不全，请检查数据",null);
        //过滤不良修改
        if (newUserRole == '0') return Result.Error("您无法将其他人修改为团队创始者，请检查数据",null);
        // 解析token
        Long userId = JwtUtils.decoderToken(Authorization);
        if (userId == null)
            return Result.Error("申请人数据不全，请检查数据", null);
        //找到申请人
        LambdaQueryWrapper<UserGroup> ulqw = new LambdaQueryWrapper<>();
        ulqw.eq(UserGroup::getUserId, userId).eq(UserGroup::getGroupId,groupId);
        UserGroup userGroup = userGroupDao.selectOne(ulqw);
        if (userGroup == null) return Result.Error("信息不全，请检查数据",null);
        //找到被修改成员
        LambdaQueryWrapper<UserGroup> be_ulqw = new LambdaQueryWrapper<>();
        be_ulqw.eq(UserGroup::getUserId, be_userId).eq(UserGroup::getGroupId,groupId);
        UserGroup be_userGroup = userGroupDao.selectOne(be_ulqw);
        if (be_userGroup == null)
            return Result.Error("被修改成员不在团队中，请检查数据",null);
        if(userGroup.getUserRole() == '0'){
            //修改权限
            be_userGroup.setUserRole(newUserRole);
            userGroupDao.updateById(be_userGroup);
            MessageUtils.sendMessage(userId,userDao.selectById(userId).getUserName(),9, Long.valueOf(groupId));
            return Result.Success("修改成功！",null);
        }
        return Result.Error("权限不足，您无法修改其他人的权限信息，请检查数据", null);
    }
    @ApiOperation("退出团队")
    @PostMapping("/quitTeam")
    public Result quitTeam(@RequestHeader String Authorization, @RequestParam Long groupId){
        //解析token
        if (Authorization == null || Authorization.equals(""))
            return Result.Error("申请人数据不全，请检查数据", null);
        Long userId = JwtUtils.decoderToken(Authorization);
        if (userId == null)
            return Result.Error("申请人数据不全，请检查数据", null);
        //找到申请人
        LambdaQueryWrapper<UserGroup> ulqw = new LambdaQueryWrapper<>();
        ulqw.eq(UserGroup::getUserId, userId).eq(UserGroup::getGroupId,groupId.toString());
        UserGroup userGroup = userGroupDao.selectOne(ulqw);
        if(userGroup == null) return Result.Error("您未加入该团队",null);
        if (userGroup.getUserRole() == '0') return Result.Error("您是团队创始者，不能退出",null);
        userGroupDao.deleteById(userGroup.getId());
        // 更新团队成员人数
        Team team = teamDao.selectById(groupId);
        team.setCurrentMemberSize(team.getCurrentMemberSize() - 1);
        teamDao.updateById(team);
        MessageUtils.sendMessage(userId,userDao.selectById(userId).getUserName(),7,groupId);
        return Result.Success("退出团队成功",null);
    }

    @GetMapping("/showUsers")
    @ApiOperation("展示成员列表")
    public Result showUsers(@RequestHeader String Authorization,
                            @RequestParam Long groupId,
                            @RequestParam(name = "currentPage", required = false, defaultValue = "1") Long currentPage,
                            @RequestParam(name = "pageSize", required = false, defaultValue = "10") Long pageSize){
        Page<TeamShowUserView> usersPage = new Page<>(currentPage, pageSize);
        //解析token
        if(Authorization == null || Authorization.equals(""))
            return Result.Error("数据不全",null);
        Long userId = JwtUtils.decoderToken(Authorization);
        if(userId == null)
            return Result.Success("未查询到当前用户信息",null);
        //找到成员
        LambdaQueryWrapper<UserGroup> uglqw = new LambdaQueryWrapper<>();
        uglqw.eq(UserGroup::getUserId, userId).eq(UserGroup::getGroupId, groupId);
        UserGroup userGroup = userGroupDao.selectOne(uglqw);
        if(userGroup == null) return Result.Success("未查询到当前用户的团队信息！", null);
//        if (userGroup.getUserRole() == '2') return Result.Error("权限不足！", null);
        Users users = userDao.selectById(userId);
        //找到该团队
        LambdaQueryWrapper<UserGroup> uglqw1 = new LambdaQueryWrapper<>();
        uglqw1.eq(UserGroup::getGroupId, groupId);
        List<TeamShowUserView> teamShowUserViews = userGroupDao.selectList(uglqw1).stream().map(userGroup1 -> {
            TeamShowUserView teamShowUserView = new TeamShowUserView();
            Users users1 = userDao.selectById(userGroup1.getUserId());
            if(users1 == null) {
                teamShowUserView.setEmail("/");
                teamShowUserView.setUserName("用户已注销！");
            }else {
                teamShowUserView.setUserName(users1.getUserName());
            }
            BeanUtils.copyProperties(userGroup1, teamShowUserView);
            teamShowUserView.setUserAvatar(userDao.selectById(userGroup1.getUserId()).getUserAvatar());
            try {
                teamShowUserView.setEmail(AESUtils.decrypt(userDao.selectById(userGroup1.getUserId()).getEmail()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            teamShowUserView.setUserGender(users.getUserGender());
            teamShowUserView.setIsInputVoice(userGroup1.getIsInputVoice());
            if (userGroup1.getUserRole() == '0') teamShowUserView.setRoleName("创始人");
            else if (userGroup1.getUserRole() == '1') teamShowUserView.setRoleName("管理员");
            else teamShowUserView.setRoleName("团队成员");
            teamShowUserView.setGroupId(groupId);
            return teamShowUserView;
        }).collect(Collectors.toList());
        List<TeamShowUserView> newTeamShowUserView = new ArrayList<>();
        //对返回的数据进行排序
        //先插入自己
        for (TeamShowUserView evenTeamShowUserView:teamShowUserViews){
            if (evenTeamShowUserView.getUserId().equals(userId)){
                newTeamShowUserView.add(evenTeamShowUserView);
                break;
            }
        }
        //插入创始人
        for (TeamShowUserView evenTeamShowUserView:teamShowUserViews){
            if (!evenTeamShowUserView.getUserId().equals(userId)) {
                if (evenTeamShowUserView.getUserRole() == '0') {
                    newTeamShowUserView.add(evenTeamShowUserView);
                }
            }
        }
        //插入管理员
        for (TeamShowUserView evenTeamShowUserView:teamShowUserViews){
            if (!evenTeamShowUserView.getUserId().equals(userId)) {
                if (evenTeamShowUserView.getUserRole() == '1') {
                    newTeamShowUserView.add(evenTeamShowUserView);
                }
            }
        }
        //插入普通成员
        for (TeamShowUserView evenTeamShowUserView:teamShowUserViews){
            if (!evenTeamShowUserView.getUserId().equals(userId)) {
                if (evenTeamShowUserView.getUserRole() == '2') {
                    newTeamShowUserView.add(evenTeamShowUserView);
                }
            }
        }
        int count = newTeamShowUserView.size();
        usersPage.setTotal(count);
        usersPage.setPages(count % pageSize == 0 ? count / pageSize : count / pageSize + 1);
        usersPage.setRecords(newTeamShowUserView);
        return Result.Success("请求成功！",usersPage);
    }
}
